package org.lightcommons.orm.hibernate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jason Green
 * @since 2007-10-11
 */
public class ConditionGroup implements Condition {
	String op = "";
	List<Condition> subs = new ArrayList<Condition>();

	public ConditionGroup(boolean orType) {
		op = orType ? " or " : " and ";
	}

	@Override
	public String toString() {
		StringBuffer b = new StringBuffer();
		for (Condition c : subs) {
			if (c.toString() == null || c.toString().length() == 0)
				continue;
			if (b.length() != 0)
				b.append(op);
			b.append(c);
		}
		return b.length() == 0 ? "" : "(" + b.toString() + ")";
	}

	public boolean isEmpty() {
		return subs.isEmpty();
	}

	public ConditionGroup add(String hql) {
		return add(new HqlCondition(hql));
	}

	public ConditionGroup add(Condition c) {
		subs.add(c);
		return this;
	}

	public ConditionGroup andGroup() {
		ConditionGroup g = new ConditionGroup(false);
		this.add(g);
		return g;
	}

	public ConditionGroup orGroup() {
		ConditionGroup g = new ConditionGroup(true);
		this.add(g);
		return g;
	}
}
